/**
 * 
 */
package com.zznode.client.wlanpolling.test;

import java.io.ByteArrayInputStream;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;

import org.w3c.dom.Node;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.Toast;

import com.zznode.client.wlanpolling.EnumRunMode;
import com.zznode.client.wlanpolling.R;
import com.zznode.client.wlanpolling.WLANPollingApplication;
import com.zznode.client.wlanpolling.WLanContext;
import com.zznode.client.wlanpolling.model.ACInfo;
import com.zznode.client.wlanpolling.model.APInfo;
import com.zznode.client.wlanpolling.model.GeneralInfo;
import com.zznode.client.wlanpolling.model.HotspotInfo;
import com.zznode.client.wlanpolling.model.LoadDicts;
import com.zznode.client.wlanpolling.model.TestResult;
import com.zznode.client.wlanpolling.model.TestResultConstants;
import com.zznode.client.wlanpolling.model.WLANPollManager;
import com.zznode.client.wlanpolling.model.WLanInfo;
import com.zznode.client.wlanpolling.other.BreakdownActivity;
import com.zznode.client.wlanpolling.service.Wifi;
import com.zznode.client.wlanpolling.service.net.EnumHttpMethod;
import com.zznode.client.wlanpolling.service.net.HttpCallback;
import com.zznode.client.wlanpolling.service.net.HttpException;
import com.zznode.client.wlanpolling.service.net.HttpExecutorFactory;
import com.zznode.client.wlanpolling.service.net.HttpGetExecutor;
import com.zznode.client.wlanpolling.service.net.HttpParam;
import com.zznode.client.wlanpolling.service.xml.XmlParserException;
import com.zznode.client.wlanpolling.service.xml.XmlXPathAdaptor;
import com.zznode.client.wlanpolling.utils.PingUtils;
import com.zznode.client.wlanpolling.utils.WLanPollingUtils;
import com.zznode.global.Global;

/**
 * 
 *
 */
public class ResConfirmActivity extends Activity implements HttpCallback, LocationListener {

	private final String TAG = getClass().getSimpleName();

	private WLANPollingApplication application;

	private ResConfirmAdapter adapter;

	private XmlXPathAdaptor xPath = null;

	private ProgressDialog pBar;
	
	private LocationManager locationManager = null;
	private String bestProvider = null;
	
	private String bssid = null;
	
	private APInfo apInfo = null;
	private HotspotInfo hotInfo = null;
	private ACInfo acInfo = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.resconfirm);
		application = (WLANPollingApplication) getApplication();
		initListView();
		showProgress();
		LoadDicts();
		String id = null;
		if(application != null){
			Wifi wifi = application.getContext().getCurrentWifi();
			if(wifi != null){
				id = wifi.getBSSID();
			}
		}
		if(bssid == null || !bssid.equals(id)){
			bssid = id;
			WLANPollManager.getWLANPollManager().loadTestResultFromDb(application.getApplicationContext(), bssid);
			retrieveResInfo();
		} else {
			WLanInfo info = WLANPollManager.getWLANPollManager().allInfo.get(bssid);
			if(info != null){
				adapter.resetWLanInfo(info);
			}
		}
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		Criteria criteria = new Criteria();
		bestProvider = locationManager.getBestProvider(criteria, false);
	}

	protected void initListView() {
		ExpandableListView elv = (ExpandableListView) this.findViewById(R.id.resList);
		LinearLayout ll = new LinearLayout(this);
		ll.setOrientation(LinearLayout.VERTICAL);
		Button btn = new Button(this);
		btn.setBackgroundResource(R.drawable.btn_testsel);
		
		if(this.getParent() instanceof WLANPollingTabActivity) {
			btn.setText("保存，进入下一步");
		} else {
			btn.setText("保存");
		}
		
		btn.setTextColor(Color.WHITE);
		btn.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				saveAndNext();
			}
			
		});
		LayoutParams params = new LayoutParams(250, LayoutParams.WRAP_CONTENT);
		params.topMargin = 10;
		params.gravity = Gravity.CENTER_HORIZONTAL;
		ll.addView(btn, params);
		elv.addFooterView(ll);
		
		adapter = new ResConfirmAdapter(this, application.getContext().getCurrentWifi());
		elv.setAdapter(adapter);
		elv.setGroupIndicator(null);
		elv.expandGroup(0);
	}
	
	private void LoadDicts(){
		//-------------覆盖方式
		LoadDicts loadDicts = new LoadDicts();
		loadDicts.setPath("/BNDICT_hotspotsovtech_NODE/");
		loadDicts.retrieveResInfo("BNDICT_hotspotsovtech");
		//-------------
		//-------------传输类型
		loadDicts = new LoadDicts();
		loadDicts.setPath("/BNDICT_transmissiontype_NODE/");
		loadDicts.retrieveResInfo("BNDICT_transmissiontype");
		//-------------
		//-------------热点类型
		loadDicts = new LoadDicts();
		loadDicts.setPath("/BNDICT_hotspottype_NODE/");
		loadDicts.retrieveResInfo("BNDICT_hotspottype");
		//-------------
		//-------------其他运营商覆盖
//		loadDicts = new LoadDicts();
//		loadDicts.setPath("/BNDICT_is_cover_by_ap_NODE/");
//		loadDicts.retrieveResInfo("BNDICT_is_cover_by_ap");
		//-------------
		Global.map.clear();
		//-------------学校小类
		loadDicts = new LoadDicts();
		loadDicts.setPath("/BNDICT_schoolsubclass_NODE/");
		loadDicts.retrieveResInfo("BNDICT_schoolsubclass");
		//-------------
		//-------------医院小类
		loadDicts = new LoadDicts();
		loadDicts.setPath("/BNDICT_hospitalsubclass_NODE/");
		loadDicts.retrieveResInfo("BNDICT_hospitalsubclass");
		//-------------
		//-------------宾馆小类
		loadDicts = new LoadDicts();
		loadDicts.setPath("/BNDICT_hotalsubclass_NODE/");
		loadDicts.retrieveResInfo("BNDICT_hotalsubclass");
		//-------------
	}
	
	private void retrieveResInfo() {
		WLanContext context = application.getContext();
		HttpGetExecutor executor = (HttpGetExecutor) HttpExecutorFactory
				.createHttpExecutor(EnumHttpMethod.GET);
		executor.setUrl(WLanPollingUtils.getDevInfoURL());
		
		//TODO 这里参数居然有一个空格
		//executor.addParam(new HttpParam("%20apmac",
		//application.getContext().getCurrentWifi().getBSSID()));
		try {
			//TODO
			if(WLanPollingUtils.RUN_MODE == EnumRunMode.DEBUG) {
				executor.addParam(new HttpParam("apmac", WLanPollingUtils.DEBUG_WIFI));
			} else {
					executor.addParam(new HttpParam("apmac", PingUtils.clearMacAdress(context.getCurrentWifi().getBSSID())));
			}
			executor.addParam(new HttpParam("UID", context.getUid()));
			executor.asyncExecute(this, 0);
		} catch (Exception e) {
			System.err.println("资源确认error:"+e);
		}
		
	}

	private void showProgress() {
		pBar = new ProgressDialog(this);
		pBar.setTitle("正在获取信息");
		pBar.setMessage("请稍候...");
		pBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		pBar.show();
	}

	@Override
	public void onReceiveData(byte[] data, final HttpException exp, int tag) {
		if(tag == 0) {
			if (exp == null) {
				try {
					final WLanInfo wlanInfo = adapter.getWLanInfo();
					
					xPath = new XmlXPathAdaptor(new ByteArrayInputStream(data));
					
					apInfo = (APInfo) wlanInfo.allInfo[0];
					hotInfo = (HotspotInfo) wlanInfo.allInfo[1];
					acInfo = (ACInfo) wlanInfo.allInfo[2];
					
					Field[] fields = APInfo.class.getFields();
					setValue(fields, apInfo);
					
					fields = HotspotInfo.class.getFields();
					setValue(fields, hotInfo);
					
					fields = ACInfo.class.getFields();
					setValue(fields, acInfo);
					
					try {
						
						if (locationManager
								.isProviderEnabled(bestProvider)) {
							Location location = locationManager
									.getLastKnownLocation(bestProvider);
							if (location != null) {
								apInfo.REAL_LNG = location.getLongitude();
								apInfo.REAL_LAT = location.getLatitude();
							}
						}
					} catch (final Exception e) {
						apInfo.REAL_LNG = 24.567;
						apInfo.REAL_LAT = 137.235;
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								Toast.makeText(getApplicationContext(), e.getMessage(),
										Toast.LENGTH_LONG).show();
							}
						});
					}
					hotInfo.REAL_LNG = apInfo.REAL_LNG;
					hotInfo.REAL_LAT = apInfo.REAL_LAT;
					
					runOnUiThread(new Runnable() {
						public void run() {
							adapter.resetWLanInfo(wlanInfo);
							pBar.cancel();
						}
					});
	
				} catch (final Exception e) {
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							pBar.cancel();
							Toast.makeText(getApplicationContext(), e.getMessage(),
									Toast.LENGTH_LONG).show();
						}
					});
				}
			} else {
				// 获取设备信息失败，出现错误
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						pBar.cancel();
						Toast.makeText(getApplicationContext(), exp.getMessage(),
								Toast.LENGTH_LONG).show();
					}
				});
			}
		} else if(tag == 1) {
			//
			if (exp == null) {
				String status = "1";
				String info = "";

				try {
					XmlXPathAdaptor xpathAdaptor = new XmlXPathAdaptor(new ByteArrayInputStream(data));
					
						Node resultCode  = (Node)xpathAdaptor.evaluate("/NODE/RESULT_CODE ", XPathConstants.NODE);
						status = resultCode.getAttributes().getNamedItem("name").getNodeValue();
						info = resultCode.getTextContent();
				} catch (XmlParserException e) {
					status = "0";
					info = e.getMessage();
				}

				if("1".equals(status)) {
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							Toast.makeText(ResConfirmActivity.this, "提交资源确认信息成功!", Toast.LENGTH_LONG).show();
						}
					});
				} else {
					final String infoT = info;
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							Toast.makeText(ResConfirmActivity.this, "提交资源确认信息失败,原因:" + infoT, Toast.LENGTH_LONG).show();
						}
					});
				}
			} else {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						Toast.makeText(getApplicationContext(), "提交资源确认信息失败:原因:" + exp.getMessage(),
								Toast.LENGTH_LONG).show();
					}
				});
			}
		}
	}

	private Node getNode(String path) {
		Node node = null;
		try {
			node = (Node) xPath.evaluate(path, XPathConstants.NODE);
		} catch (XmlParserException e) {
			Log.e(TAG, e.getMessage());
		}
		return node;
	}
	
	/**
	private NodeList getNodes(String path) {
		NodeList nodes = null;
		try {
			nodes = (NodeList) xPath.evaluate(path, XPathConstants.NODESET);
		} catch (XmlParserException e) {
			Log.e(TAG, e.getMessage());
		}
		return nodes;
	}
	
	private void getDetailedInfo(final GeneralInfo instance, final Field field, final String typeId){
		WLanContext context = application.getContext();
		HttpGetExecutor executor = (HttpGetExecutor) HttpExecutorFactory
				.createHttpExecutor(EnumHttpMethod.GET);
		executor.setUrl(WLanPollingUtils.getDictsURL());
		executor.addParam(new HttpParam("dictTypeId", typeId));
		executor.addParam(new HttpParam("UID", context.getUid()));
		executor.asyncExecute(new HttpCallback(){

			@Override
			public void onReceiveData(byte[] data, HttpException exp,
					int tag) {
				if(exp == null){
					try {
						xPath = new XmlXPathAdaptor(new ByteArrayInputStream(data));
						NodeList nodes = getNodes("/" + typeId + "_NODE/BUSINID");
						String fieldValue = (String)field.get(instance);
						for(int i = 0; i < nodes.getLength(); i++){
							Node node = nodes.item(i);
							String value = node.getFirstChild().getNodeValue();							
							if(fieldValue.equals(value)){
								NamedNodeMap map = node.getAttributes();
								Node n = map.getNamedItem("name");
								field.set(instance, n.getNodeValue());
								break;
							}
						}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			
		}, 0);
	}
	 */
	private void setValue(Field[] fields, GeneralInfo instance)
			throws Exception {
		TestResult testResult = WLANPollManager.getWLANPollManager().getTestResult();
		for (Field field : fields) {
			String name = field.getName();
			Node node = getNode("/NODE/" + name);
			setFieldValue(field, node, testResult, instance);
			
			//保存AP的经纬度，供其它地方使用
			if("AP_LONGTITUDE".equals(name) && node != null) {
				application.getContext().setApLongtitude(node.getTextContent());
			}
			if("AP_LATITUDE".equals(name)) {
				application.getContext().setApLatitude(node.getTextContent());
			}
			
//			if("HOT_TYPE".equals(name)){
//				getDetailedInfo(instance, field, "BNDICT_hotspottype");
//			}
//			if("HOT_CLASS".equals(name)){
//				getDetailedInfo(instance, field, "BNDICT_schoolsubclass");
//			}
		}
	}
	
	private void setFieldValue(Field field, Node node, TestResult testResult, Object instance) throws Exception {
		String attributeName = TestResultConstants.ResultMaps.get(field.getName());
		Field testResultField = null;
		if(attributeName != null) {
			testResultField = TestResult.class.getField(attributeName);
		}
		if (node != null) {
			String value = node.getTextContent();
			String valueLocal = null;
			if(testResultField != null) {
				valueLocal = (String)testResultField.get(testResult);
			}
			if(field.getName().equals("AP_MAC")){
				field.set(instance, value);
			}
			else {
				if(this.getParent() instanceof WLANPollingTabActivity){
					field.set(instance,  value == null || "".equals(value) ? valueLocal : value);
				}
				else {
					field.set(instance,  valueLocal == null || "".equals(valueLocal) ? value : valueLocal);
				}
				
			}
		}
	}

	@Override
	public void onLocationChanged(Location location) {
		if (apInfo != null) {
			apInfo.REAL_LNG = location.getLongitude();
			apInfo.REAL_LAT = location.getLatitude();
		}
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		locationManager.requestLocationUpdates(bestProvider, 20000, 1, this);
	}
	
	protected void saveAndNext(){
		WLANPollManager.getWLANPollManager().allInfo.put(bssid, adapter.getWLanInfo());

		// AP
		final Map<String, Object> values = new HashMap<String, Object>();
		
		Wifi wifi = application.getContext().getCurrentWifi();
		values.put(TestResultConstants.SSID, wifi.getSSID());
		values.put(TestResultConstants.APCODENO, apInfo.AP_CODE);
		values.put(TestResultConstants.APCONTACTFUN, apInfo.AP_CONTRACTFUNC);
		values.put(TestResultConstants.APCONTACTPERSON, apInfo.AP_CONTRACTPERSON);
		values.put(TestResultConstants.APCOVERAREA, apInfo.AP_COVER);
		values.put(TestResultConstants.APCOVERTECH, apInfo.AP_COVER_TYPE);
		
		values.put(TestResultConstants.APDEVNAME, apInfo.DEV_ID);
		values.put(TestResultConstants.APIP, apInfo.AP_IP);
		values.put(TestResultConstants.APLEVEL, apInfo.AP_LEVEL);
		values.put(TestResultConstants.SYAPMAC, apInfo.AP_MAC);
		values.put(TestResultConstants.APSERNO, apInfo.AP_SN);
//		values.put(TestResultConstants.APTRANTYPE, apInfo.AP_TRANSFER_TYPE);
		values.put(TestResultConstants.APWORKTIME, apInfo.AP_RUNTIME);
		values.put(TestResultConstants.APLAT, apInfo.AP_LATITUDE);
		values.put(TestResultConstants.APLON, apInfo.AP_LONGTITUDE);
		
		//问题跟踪表0416
		values.put(TestResultConstants.APVLAN, apInfo.AP_VLAN_ID);
		values.put(TestResultConstants.APVERSION, apInfo.AP_SOFT_VERSION);
		values.put(TestResultConstants.APLOCATION, apInfo.AP_DEV_POSITION);
		values.put(TestResultConstants.APSEC1, apInfo.AP_SECTION_NO1);
		values.put(TestResultConstants.APSEC2, apInfo.AP_SECTION_NO2);
		
		//增加AP_REMARK 
		//values.put(TestResultConstants.AP_REMARK, apInfo.AP_REMARK);
		
		// AC //问题跟踪表0416
		values.put(TestResultConstants.APTRANTYPE, acInfo.AP_TRANSFER_TYPE);
		values.put(TestResultConstants.AP_SWITCH, acInfo.AP_SWITCH);
		values.put(TestResultConstants.AP_SWITCH_PORT, acInfo.AP_SWITCH_PORT);
		values.put(TestResultConstants.AP_SWITCH_BANDWIDTH, acInfo.AP_SWITCH_BANDWIDTH);
		
		// Hotspot
		values.put(TestResultConstants.HOTADDRESS, hotInfo.HOT_ADDRESS);
		values.put(TestResultConstants.HOTCODE, hotInfo.HOT_CODENO);
		values.put(TestResultConstants.HOTLAT, hotInfo.HOT_LATITUDE);
		values.put(TestResultConstants.HOTLON, hotInfo.HOT_LONGITUDE);
		values.put(TestResultConstants.HOTNAME, hotInfo.HOT_NAME);
		values.put(TestResultConstants.HOTSUBTYPE, hotInfo.HOT_CLASS);
		values.put(TestResultConstants.HOTTYPE, hotInfo.HOT_TYPE);
		
		//问题跟踪表0416
		values.put(TestResultConstants.HOTLANDMARK, hotInfo.HOT_LANDMARK);
		values.put(TestResultConstants.HOTSPOTTEL, hotInfo.HOTSPOT_TEL);
		values.put(TestResultConstants.HOTIPREGION, hotInfo.HOT_IPADDRESS);
		//String apMac = application.getContext().getCurrentWifi().getBSSID();
		
		//0418保存终端设备信息
		values.put(TestResultConstants.PHONEMAC, application.getContext().getCurrentWifi().getMacAddress());
		values.put(TestResultConstants.PHONECOMPANY, Build.MANUFACTURER);
		values.put(TestResultConstants.PHONETYPE, Build.PRODUCT + "/" + Build.MODEL);
		values.put(TestResultConstants.SSID, application.getContext().getCurrentWifi().getSSID());
		
		WLANPollManager.getWLANPollManager().updateTestResult(application.getApplicationContext(), bssid, values);
		
		if(this.getParent() instanceof WLANPollingTabActivity) {
			WLANPollingTabActivity tab = (WLANPollingTabActivity)this.getParent();
			int tabIndex = tab.getTabHost().getCurrentTab();
			if (tabIndex < 3) {
				tabIndex++;
				tab.getTabHost().setCurrentTab(tabIndex);
			}
		} else {
			//需要提交到服务器上
			WLANPollManager.getWLANPollManager().postResourceInfo(this, bssid, values);
		}
	}
}
